import pygame, sys
from settings import *
from level import Level
from menu import MainMenu, PlayerMenu, DeathMenu

class GameState:
    """游戏状态枚举"""
    MAIN_MENU = 'main_menu'
    PLAYING = 'playing'
    PAUSED = 'paused'
    DEATH = 'death'

class Game:
    def __init__(self):
        pygame.init()
        pygame.mixer.init()  # 初始化音频系统
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        pygame.display.set_caption("My Game")
        self.clock = pygame.time.Clock()
        
        # 加载音效
        self.load_sounds()
        
        # 加载并播放背景音乐
        try:
            pygame.mixer.music.load('./music/backg/backmusic.wav')
            pygame.mixer.music.set_volume(0.5)  # 设置音量为50%
            pygame.mixer.music.play(-1)  # -1表示循环播放
        except Exception as e:
            print(f"无法加载背景音乐: {e}")
        
        # 游戏状态
        self.state = GameState.MAIN_MENU
        self.running = True
        
        # 组件初始化
        self.main_menu = MainMenu()
        self.player_menu = PlayerMenu()
        self.level = None
        self.death_menu = None
        
        # 暂停相关
        self.last_pause_time = 0
        self.pause_cooldown = 500  # 500ms
        self.game_surface = None
        
    def load_sounds(self):
        """加载音效"""
        self.sounds = {
            'level_up': pygame.mixer.Sound('./music/music/level_up/level_up.wav'),
            'dash': pygame.mixer.Sound('./music/music/dash/dash.wav'),
            'axe': pygame.mixer.Sound('./music/music/axe/axe.wav'),
            'hoe': pygame.mixer.Sound('./music/music/hoe/hoe.wav'),
            'hurt': pygame.mixer.Sound('./music/music/hurt/hurt.wav')
        }
        # 设置音效音量
        for sound in self.sounds.values():
            sound.set_volume(0.4)  # 设置音效音量为40%
            
    def play_sound(self, sound_name):
        """播放指定音效"""
        if sound_name in self.sounds:
            self.sounds[sound_name].play()
        
    def run(self):
        while self.running:
            events = pygame.event.get()
            keys = pygame.key.get_pressed()
            current_time = pygame.time.get_ticks()
            
            # 处理退出
            for event in events:
                if event.type == pygame.QUIT:
                    self.running = False
                    break
            
            # 处理暂停
            if keys[pygame.K_p] and current_time - self.last_pause_time > self.pause_cooldown:
                self.last_pause_time = current_time
                if self.state == GameState.PLAYING:
                    self.game_surface = self.screen.copy()
                    self.state = GameState.PAUSED
                elif self.state == GameState.PAUSED:
                    self.state = GameState.PLAYING
            
            # 状态处理
            if self.state == GameState.MAIN_MENU:
                menu_result = self.main_menu.run()
                if menu_result is False:
                    self.running = False
                elif menu_result is True:
                    self.level = Level()
                    self.level.set_game(self)  # 设置对 Game 实例的引用
                    self.death_menu = DeathMenu(self.level.player)
                    self.state = GameState.PLAYING
                    # 重新播放背景音乐
                    pygame.mixer.music.play(-1)
                    
            elif self.state == GameState.PLAYING:
                dt = self.clock.tick() / 1000
                self.level.run(dt)
                
                # 检查玩家是否死亡
                if self.level.player.health <= 0:
                    self.game_surface = self.screen.copy()
                    self.state = GameState.DEATH
                    # 停止背景音乐
                    pygame.mixer.music.stop()
                
                pygame.display.update()
                
            elif self.state == GameState.PAUSED:
                # 使用保存的游戏画面
                if self.game_surface:
                    self.screen.blit(self.game_surface, (0,0))
                
                # 显示暂停菜单
                action = self.player_menu.display(events)
                
                if action == 'back':
                    self.state = GameState.PLAYING
                elif action == 'backmain':
                    # 重置游戏状态，返回主菜单
                    self.state = GameState.MAIN_MENU
                    self.level = None
                    self.game_surface = None
                    # 重新播放背景音乐
                    pygame.mixer.music.play(-1)
                elif action == 'exit':
                    self.running = False
                
                pygame.display.update()
                
            elif self.state == GameState.DEATH:
                # 显示死亡时的游戏画面
                if self.game_surface:
                    self.screen.blit(self.game_surface, (0,0))
                
                # 显示死亡菜单
                self.death_menu.draw()
                
                # 处理死亡菜单输入
                for event in events:
                    action = self.death_menu.handle_input(event)
                    if action == 'restart':
                        # 重新开始游戏
                        self.level = Level()
                        self.level.set_game(self)  # 设置对 Game 实例的引用
                        self.death_menu = DeathMenu(self.level.player)
                        self.state = GameState.PLAYING
                        # 重新播放背景音乐
                        pygame.mixer.music.play(-1)
                    elif action == 'quit':
                        self.running = False
                
                pygame.display.update()
        
        pygame.quit()
        sys.exit() 